﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

using System.Globalization;
using System.Threading;
using WebMVC.Models;
using WebMVC.Resources.Models.Account;


namespace WebMVC.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public AccountController()
            : this(null, null)
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments in AccountModels.cs for more information.
        public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
        {
            FormsService = formsService ?? new FormsAuthenticationService();
            MembershipService = membershipService ?? new AccountMembershipService();
        }

        public IFormsAuthenticationService FormsService
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (requestContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
            else
            {
                base.Initialize(requestContext);
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            base.OnActionExecuting(filterContext);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult ChangeLanguage(string lang, string returnUrl)
        {
            if (returnUrl.Length >= 3)
            {
                returnUrl = returnUrl.Substring(3);
            }

            return Redirect("/" + lang.ToString() + returnUrl);
        }

        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {   
                    ErrorPair<string,string> error = ErrorCodeToString(createStatus);
                    ModelState.AddModelError(error.Key, error.Message);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private static ErrorPair<string,string> ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return new ErrorPair<string,string>("UserName", Validation.DuplicateUserName);

                case MembershipCreateStatus.DuplicateEmail:
                    return new ErrorPair<string, string>("Email", Validation.DuplicateEmail);

                case MembershipCreateStatus.InvalidPassword:
                    return new ErrorPair<string, string>("Password", Validation.InvalidPassword);

                case MembershipCreateStatus.InvalidEmail:
                    return new ErrorPair<string, string>("Email", Validation.InvalidEmail);

                case MembershipCreateStatus.InvalidAnswer:
                    return new ErrorPair<string, string>(null, Validation.InvalidAnswer);

                case MembershipCreateStatus.InvalidQuestion:
                    return new ErrorPair<string, string>(null, Validation.InvalidQuestion);

                case MembershipCreateStatus.InvalidUserName:
                    return new ErrorPair<string, string>("UserName", Validation.InvalidUserName);

                case MembershipCreateStatus.ProviderError:
                    return new ErrorPair<string, string>(null, Validation.ProviderError);

                case MembershipCreateStatus.UserRejected:
                    return new ErrorPair<string, string>(null, Validation.UserRejected);

                default:
                    return new ErrorPair<string, string>(null, Validation.MembershipDefault);
            }
        }

    }

    class ErrorPair<E,T>
    {
        public E Key { get; set; }
        public T Message { get; set; }
        public ErrorPair(E key, T message){
            Key = key;
            Message = message;
        }
    }
}
